<?php
/**
 * Контроллер администраторских действий.
 *
 * @property Zend_Controller_Request_Http $_request
 */
class Users_AdminController extends Users_Model_Abstract_AdminController {
	const FORM_CONFIG_REGISTER = 'forms/register';
	const FORM_CONFIG_ASK_USER_ID = 'forms/ask_user_id';
	const FORM_CONFIG_ADD_MESSAGE = 'forms/add_message';

    const PROFILE_HELPER = 'Profile';

	/**
	 * Настройки столбцов таблицы списка пользователей.
	 *
	 * @var array
	 */
	protected $_aUserListColumns = array(
		'Логин'       => array('name' => 'login',      'width' => 180),
		'Эл.почта'    => array('name' => 'email',      'width' => 260),
		'Фамилия'     => array('name' => 'last_name',  'width' => 260),
		'Имя'         => array('name' => 'first_name', 'width' => 180),
		'Отчество'    => array('name' => 'patronymic', 'width' => 140),
		'Карма'       => array('name' => 'rating',     'width' => 80),
		'Регистрация' => array('name' => 'created',    'width' => 160),
		'Флаги'       => array('name' => 'flags',      'width' => 30,  'sortable' => false),
	);

	/**
	 * (non-PHPdoc)
	 * @see library/Zend/Controller/Zend_Controller_Action#init()
	 */
	public function init() {
		parent::init();

        /** @var Workset_Controller_Action_Helper_ActionLayout $helper */
        $helper = $this->_helper->getHelper('ActionLayout');
        $helper->addScriptFile('/js/utilites.js');
	}

	/**
	 * Основная страница администрирования модуля "users".
     *
     * @return void
	 */
	public function indexAction() {
		try {
			$this->_response->setRedirect('/users/admin/list-user', 302);
		}
		catch (Exception $e) {
            /** @var Workset_Controller_Action_Helper_Application $helper */
            $helper = $this->_helper->getHelper('Application');
            $helper->throwException($e);
		}
	}

    /**
     * Действие по авторизации пользователя.
     *
     * @return void
     */
	public function loginAction() {
		// Создание объекта формы.
        /** @var Workset_Controller_Action_Helper_ModuleConfig $helperModuleConfig */
        $helperModuleConfig = $this->_helper->getHelper('ModuleConfig');
        $formConfig = $helperModuleConfig->getConfig('forms/login');
		$form = new Users_Form_Login($formConfig);

        /** @var Workset_Controller_Action_Helper_Url $helperUrl */
        $helperUrl = $this->_helper->getHelper('Url');
		$form->setAction(
            $helperUrl->simple('index', 'login', null)
		);

		$form->addActionParams(array(
			'backurl' => $this->_request->getParam('backurl', $this->_request->getHeader('referer')),
		));

		// Запоминаем объект формы для вывода в шаблоне вида.
        /** @noinspection PhpUndefinedFieldInspection */
        $this->view->form = $form;
        $this->view->message = $this->_actionConfig['auth_message'];
	}

	/**
	 * Начальное отображение списка пользователей.
     *
     * @return void
	 */
	public function listUserAction() {
        /** @var Workset_Controller_Action_Helper_Url $helperUrl */
        $helperUrl = $this->_helper->getHelper('Url');

		// Формирование объекта таблицы JQueryGrid.
        /** @noinspection PhpUndefinedFieldInspection, PhpUndefinedMethodInspection */
        $this->view->jqgrid = $this->view->JQueryGrid()
			->setTableId('UsersList')
			->setPagerId('UsersListPager')
			->setOptions(array(
				'caption' => $this->_actionConfig['jqgrid_userlist_caption'],
				'url' => $helperUrl->simple('list-user-model'),
				'mtype' => 'GET',
				'colNames' => $this->_actionConfig['jqgrid_userlist_col_names'], //array_keys($this->_aUserListColumns),
				'colModel' => $this->_actionConfig['jqgrid_userlist_col_model'], //array_values($this->_aUserListColumns),
				'sortname' => 'login',
				'multiselect' => true,
				'editurl' => $helperUrl->simple('ajax-user-operations'),
				/*'subGrid' => true,
				'subGridRowExpanded' => new Zend_Json_Expr(
					$this->_helper->getHelper('Application')->jsFunction('getUserListAjaxForm', array('subgrid_id', 'row_id'), true)
				),*/
			))
       		->enableNavGrid(array(
            	'add' => false,
	            'edit' => false,
    	    ))
			->invokeParams(array(
				'groupUrl' => $helperUrl->simple('list-user-group'),
			))
			->addNavButton('b_col_chooser', array(
				'caption' => '',
				'position' => 'last',
				'title' => 'Выбор и перемещение столбцов таблицы',
				'onClickButton' => new Zend_Json_Expr(
					$this->_helper->application->jsFunction('columnChooser', null, true)
				)
			))
			->addNavButton('b_group', array(
				'buttonicon' => 'ui-icon-document',
				'caption' => 'Группы доступа',
				'position' => 'last',
				'onClickButton' => new Zend_Json_Expr(
					$this->_helper->application->jsFunction('changeGroup', null, true)
				)
			));

		// Уточнение путей.
        /** @var Workset_Controller_Action_Helper_HttpUri $helperHttpUri  */
        $helperHttpUri = $this->_helper->getHelper('HttpUri');
        /** @noinspection PhpUndefinedFieldInspection */
        $this->view->jqgrid->gridScripts[] = '/js/jquery.form.js';

        $this->view->addUserUrl = $helperHttpUri->getUri('/users/admin/add-user');
		$this->view->addUserUrl->setQuery(array(
			'backurl' => (string)$helperHttpUri->getUri(),
		));

        $this->view->editUserUrl = $helperHttpUri->getUri('/users/admin/profile');
		$this->view->editUserUrl->setQuery(array(
			'backurl' => (string)$helperHttpUri->getUri(),
		));

		$this->view->jsObject = $this->_helper->application->jsFunctionName();
	}

	/**
	 * Получение данных для таблицы списка пользователей.
     *
     * @return void
	 */
	public function listUserModelAction() {
        /** @var stdClass $oResponse */
        /** @var Users_Model_User $oUser */

		// Получение запрашиваемого списка пользователей.
		foreach ($this->_getList('Users_Model_User_Db',array(),$this->_aUserListColumns,$oResponse) as $oUser) {
            /** @noinspection PhpUndefinedFieldInspection, PhpUndefinedMethodInspection */
            $oResponse->rows[] = array(
				'id' => 'u'.$oUser->getId(),
				'cell' => array(
					$oUser->getLogin(),
					$oUser->getEMail(),
					$oUser->getLastName(),
					$oUser->getFirstName(),
					$oUser->getPatronymic(),
					$oUser->getRating(),
					$this->view->ClientDateTime($oUser->getCreated(),'d.m.Y H:i')->direct(),
					($oUser->isAdmin() ? 'A' : '_'),
				),
			);
		}

		// Вывод данных для ответа на AJAX запрос.
        /** @var Zend_Controller_Action_Helper_Json $helperJson */
		$helperJson = $this->_helper->getHelper('Json');
        $helperJson->sendJson($oResponse);
	}

	/**
	 * Изменение записи пользователя.
     *
     * @return void
	 */
	public function ajaxUserOperationsAction() {
        /** @var Zend_Controller_Action_Helper_ViewRenderer $helperViewRender */
        $helperViewRender = $this->_helper->getHelper('ViewRenderer');
		$helperViewRender->setNoRender(true);

		switch ($this->_request->getParam('oper')) {
			case 'add':
				$this->_response->setHttpResponseCode(403);
				break;

			case 'edit':
				$this->_response->setHttpResponseCode(403);
				break;

			// Удаление записей пользователей.
			case 'del':
				// Проверка наличия прав на удаление пользователя.
				if (!Users_Model_User::getUser()->isAllowed('AlienProfiles','delete')) {
					throw new Zend_Exception('You do not have right to delete this profile.',403);
				}

				if (Users_Model_User::getUser()->isAllowed('UsersList','delete')) {
					$iIds = preg_split('~\D+~',$this->_request->getParam('id'),-1,PREG_SPLIT_NO_EMPTY);
					$iIds = array_unique(array_filter(array_map('intval',$iIds)));

					foreach ($iIds as $iId) {
						try	{
							if (!Users_Model_User::getById($iId)->isAdmin()) {
								Users_Model_User::getById($iId)->delete();
							}
						}
						catch (Exception $oException) {
						}
					}
				}
				else {
					$this->_response->setHttpResponseCode(403);
				}

				break;

			default:
				$this->_response->appendBody('Unknown value for param "oper".');
				$this->_response->setHttpResponseCode(500);
		}
	}

	/**
	 * Добавление нового пользователя.
     *
     * @return void
	 */
	public function addUserAction() {
        /** @var Workset_Controller_Action_Helper_ModuleConfig $helperModuleConfig */
        $helperModuleConfig = $this->_helper->getHelper('ModuleConfig');

		// Создание объекта формы.
		$oForm = new Users_Form_Login($helperModuleConfig->getConfig(self::FORM_CONFIG_REGISTER));

        //транслятор формы
        $oForm->setTranslator(
            $this->_translate,
            $helperModuleConfig->getConfig(array('lang', $this->_locale, 'validators'), null, true)
        );

		// В случае наличия POST данных, начинаем их обработку.
		if ($this->_request->isPost()) {
			$aPost = $this->_request->getPost();

			// Если данные валидны, то регистрируем пользователя.
			if ($oForm->isValid($aPost)) {
				$sLogin = $oForm->getValue('user_login');
				$sPassword = $oForm->getValue('user_password');

				$oUser = Users_Model_User_Db::addUser(array(
					'login' => $sLogin,
					'password' => Workset_Auth::getInstance()->getPasswordHash($sLogin,$sPassword),
					'email' => $oForm->getValue('user_email'),
				));

				// Перенаправления...
				if ($this->_request->getParam('backurl')) {
					// Перенаправление по обратному адресу.
					$this->_redirectToBackUrl();
				}
				else {
					// Перенаправление на профиль пользователя.
					$aParams = $this->_request->getParams();
					$this->_redirect("/$aParams[module]/$aParams[controller]/profile?id=".$oUser->getId());
				}
			}
		}

		// Запоминаем объект формы для вывода в шаблоне вида.
        /** @noinspection PhpUndefinedFieldInspection */
        $this->view->form = $oForm;
	}

    /**
     * @return void
     */
	public function listUserGroupAction() {
		$userId = (int)$this->_getParam('id');

        $user = Users_Model_User::getById($userId);

        $groupStorage = new Users_Model_Access_Group_Storage_Table();

        $groups = $groupStorage->getUserGroups($user)->toArray('id');

		$this->_addNavItem(array(
            'label' => $user->getLogin(),
            'title' => $user->getLogin(),
            'id' => 'id'.$user->getId(),
            'params' => array('id' => $user->getId())
        ));

        $this->view->jqgrid = $this->view->JQueryGrid()
                ->setTableId('groupList1')
                ->setPagerId('groupPager1')
                ->setOptions(array(
                    'caption' => $this->_actionConfig['jqgrid_group_caption'],
                    'url' => $this->_helper->url('list-group-model', null, null, array('diff' => $groups)),
                    'mtype' => 'GET',
                    'colNames' => array_values($this->_actionConfig['jqgrid_group_col_names']),
                    'colModel' => array_values($this->_actionConfig['jqgrid_group_col_model']),
                    'sortname' => 'id',
                    'sortorder' => "desc",
                    'viewrecords' => true,
                    'editurl'   => $this->_helper->url('ajax-group-operations'),
                    'autowidth' => false,
                    'rowNum' => 20,
                    'width' => 400
                ))
                ->invokeParams(array(
					'nodeid' => $user->getId(),
					'url' => $this->_helper->url('add-user-group')
				))
				->addMethod('gridDnD', array(
					'connectWith' => '#groupList2',
					'ondrop' => new Zend_Json_Expr(
						$this->_helper->application->jsFunction(
							'addItem',
							array('evt', 'context'),
							true
						)
					),
				))
				->gridComplete(false);

        $this->view->selectedjqgrid = $this->view->JQueryGrid()->getNewInstance()
                ->setTableId('groupList2')
                ->setPagerId('groupPager2')
                ->setOptions(array(
                    'caption' => $this->_actionConfig['jqgrid_selected_group_caption'],
                    'datatype' => $groups ? 'json' : 'local',
                    'url' => $this->_helper->url('list-group-model', null, null, array('intersect' => $groups)),
                    'mtype' => 'GET',
                    'colNames' => array_values($this->_actionConfig['jqgrid_group_col_names']),
                    'colModel' => array_values($this->_actionConfig['jqgrid_group_col_model']),
                    'sortname' => 'id',
                    'sortorder' => "desc",
                    'viewrecords' => true,
                    'editurl'   => $this->_helper->url('ajax-group-operations'),
                    'autowidth' => false,
                    'rowNum' => 20,
                    'width' => 400
                ))
                ->invokeParams(array(
                    'nodeid' => $user->getId(),
                    'url' => $this->_helper->url('delete-user-group')
                ))
                ->addMethod('gridDnD', array(
                    'connectWith' => '#groupList1',
                    'ondrop' => new Zend_Json_Expr(
                        $this->_helper->application->jsFunction(
                            'removeItem',
                            array('evt', 'context'),
                            true
                        )
                    ),
                ))
                ->gridComplete(false);

		$this->view->jsObject = $this->_helper->application->jsFunctionName();
        $this->view->backurl = $this->_helper->url('list-user');
        $this->view->backurlLabel = $this->_actionConfig['backurl_label'];

        $this->render('select-group');
	}

    public function addUserGroupAction() {

        $this->_helper->viewRenderer->setNoRender(true);

        $userId = (int)$this->_getParam('nodeid');
        $groupId = (int)$this->_getParam('id');

        if ($userId < 1 || $groupId < 1) {
            throw $this->_helper->application->throwException('Wrong request params', 404);
        }

        $user = Users_Model_User::getById($userId);
        $groupStorage =  new Users_Model_Access_Group_Storage_Table();
        $group = $groupStorage->getOne($groupId);

        $groupStorage->linkToObject($group, $user);

        if (!$this->_request->isXmlHttpRequest()) {
            $redirect = $this->_helper->url('list-user');
            $this->_redirect($redirect);
        }

    }

    public function deleteUserGroupAction() {
        $this->_helper->viewRenderer->setNoRender(true);

        $userId = (int)$this->_getParam('nodeid');
        $groupId = (int)$this->_getParam('id');

        if ($userId < 1 || $groupId < 1) {
            throw $this->_helper->application->throwException('Wrong request params', 404);
        }

        $groupStorage =  new Users_Model_Access_Group_Storage_Table();

        $user = Users_Model_User::getById($userId);
        $group = $groupStorage->getOne($groupId);

        $groupStorage->unlinkObject($group, $user);

        if (!$this->_request->isXmlHttpRequest()) {
            $redirect = $this->_helper->url('list-user');
            $this->_redirect($redirect);
        }
    }

	/**
	 * Отображение профайла пользователя.
	 */
	public function profileAction() {
        /** @var Users_Helper_Profile $profile */
        $profile = $this->_helper->getHelper(self::PROFILE_HELPER);

		// Проверка наличия в запросе параметра - идентификатора пользователя.
		if (!$this->_testUserId()) {
			return;
		}

		// Инициализация объектов формы и пользователей.
		$oForm = $profile->getProfileForm();
		$oUser = $profile->getProfileUser();

        //транслятор формы
        $oForm->setTranslator(
            $this->_translate,
            $this->_helper->moduleConfig->getConfig(array('lang', $this->_locale, 'validators'), null, true)
        );

		// В случае наличия POST данных, начинаем их обработку.
		$bValid = $this->_request->isPost() && $profile->validProfileForm($oForm);

		// Вызываем action'ы для всех полей.
		// $this->profileLoginAction(true);
		$this->profileLastNameAction(true);
		$this->profileFirstNameAction(true);
		$this->profilePatronymicAction(true);
		$this->profileEmailAction(true);
		$this->profileNewPasswordAction(true);
		$this->profileEmailMessageAction(true);

		// Сохраняем все внесённые изменения.
		if ($bValid) {
			$oUser->save();

            $this->_redirect(
                $this->_helper->url('list-user')
            );
		}
		else { // Копируем значения из глобальной формы.

            $aUserFields = $oUser->toArray();
            $aUserFields = $this->_helper->utils->addPrefix($aUserFields, 'user');

            /** @var Zend_Form_Element $oElement */
			foreach ($profile->getProfileForm(null, true)->getElements() as $sName => $oElement) {

                $value = $oElement->getValue();
                if (empty($value)) {
                    $value = isset($aUserFields[$sName]) ? $aUserFields[$sName] : null;
                }

                if ($value) {
					$oForm->getElement($sName)->setValue($value);
				}
			}
		}

		// Запоминаем объекты для вывода в шаблоне.
        /** @noinspection PhpUndefinedFieldInspection */
        $this->view->form = $oForm;
		$this->view->login = $oUser->getLogin();

		// Если передавались POST данные и они не прошли валидацию, то возращаем
		// код ответа не 200, а 202. Эти коды обрабатываются при AJAX запросах
		// на стороне клиента.
		if ($this->_request->isPost() && !$bValid) {
			$this->_response->setHttpResponseCode(202);
		}
	}

	/**
	 * Удаление профиля пользователя.
	 */
	public function profileDeleteAction() {
        /** @var Users_Helper_Profile $profile */
        $profile = $this->_helper->getHelper(self::PROFILE_HELPER);

		// Проверка наличия в запросе параметра - идентификатора пользователя.
		if (!$this->_testUserId('/users/admin/profile-delete')) {
			return;
		}

		// Инициализация объекта пользователя.
        $profile->setProfileForm(null);
		$oUser = $profile->getProfileUser();

		// Проверка наличия прав на удаление пользователя.
		if ($oUser->isAdmin() || !Users_Model_User::getUser()->isAllowed('AlienProfiles','delete')) {
			throw new Zend_Exception('You do not have right to delete this profile.',403);
		}

		// Выполнение операции удаления пользователя и перенаправления клиента.
		$oUser->delete();
		$this->_redirectToBackUrl();
	}

	/**
	 * Изменение фамилии пользователя.
	 */
	public function profileLastNameAction($bNotSave = false) {
        /** @var Users_Helper_Profile $profile */
        $profile = $this->_helper->getHelper(self::PROFILE_HELPER);
		$profile->profileLastNameAction($bNotSave);
	}

	/**
	 * Изменение имени пользователя.
	 */
	public function profileFirstNameAction($bNotSave = false) {
		/** @var Users_Helper_Profile $profile */
        $profile = $this->_helper->getHelper(self::PROFILE_HELPER);
		$profile->profileFirstNameAction($bNotSave);
	}

	/**
	 * Изменение отчества пользователя.
	 */
	public function profilePatronymicAction($bNotSave = false) {
		/** @var Users_Helper_Profile $profile */
        $profile = $this->_helper->getHelper(self::PROFILE_HELPER);
		$profile->profilePatronymicAction($bNotSave);
	}

	/**
	 * Изменение электронного адреса пользователя.
	 */
	public function profileEmailAction($bNotSave = false) {
		/** @var Users_Helper_Profile $profile */
        $profile = $this->_helper->getHelper(self::PROFILE_HELPER);
		$profile->profileEmailAction($bNotSave,true);
		$bNotSave || $profile->getProfileUser()->save();
	}

	/**
	 * Изменение флага отправки копий внутренних сообщения на e-mail.
	 */
	public function profileEmailMessageAction($bNotSave = false) {
		/** @var Users_Helper_Profile $profile */
        $profile = $this->_helper->getHelper(self::PROFILE_HELPER);
		$profile->profileEmailMessageAction($bNotSave);
	}

	/**
	 * Задание нового пароля пользователя.
	 */
	public function profileNewPasswordAction($bNotSave = false) {
		/** @var Users_Helper_Profile $profile */
        $profile = $this->_helper->getHelper(self::PROFILE_HELPER);
		$profile->profileNewPasswordAction($bNotSave);
	}

	/**
	 * Создание нового сообщения.
	 */
	public function addMessageAction() {
		// Создание объекта формы.
		$aFormConfig = $this->_helper->moduleConfig(self::FORM_CONFIG_ADD_MESSAGE);
		$oForm = new Users_Form_Login($aFormConfig);

		// В случае наличия POST данных, начинаем их обработку.
		if ($this->_request->isPost()) {
			$aPost = $this->_request->getPost();

			// Если данные валидны, то регистрируем пользователя.
			if ($oForm->isValid($aPost)) {
				try {
					$iTargetId = Users_Model_User::getByLogin($oForm->getValue('user_login'))->getId();
				}
				catch (Exception $oException) {
					$iTargetId = 0;
				}

				Users_Model_Message::send($oForm->getValue('subject'),$oForm->getValue('message'),$iTargetId);

				// Перенаправления...
				if ($this->_request->getParam('backurl')) {
					// Перенаправление по обратному адресу.
					$this->_redirectToBackUrl();
				}
				else {
					// Перенаправление на список сообщений.
					$aParams = $this->_request->getParams();
					$this->_redirect("/$aParams[module]/$aParams[controller]/list-message");
				}
			}
		}

		// Запоминаем объект формы для вывода в шаблоне вида.
		$this->view->form = $oForm;
	}

	/**
	 * Настройки столбцов таблицы списка пользователей.
	 *
	 * @var array
	 */
	protected $_aMessageListColumns = array(
		'Время'        => array('name' => 'created',    'width' => 100),
		'Заголовок'    => array('name' => 'subject',    'width' => 180),
		'Пользователю' => array('name' => 'target',     'width' => 180),
		'От'           => array('name' => 'created_by', 'width' => 180),
	);

	/**
	 * Отображение всех сообщений системы.
	 */
	public function listMessageAction() {
		if (!Users_Model_User::getUser()->isAllowed('AlienMessages','read')) {
			$this->_helper->viewRenderer->setNoRender(true);
			$oException = new Zend_Exception('You do not have rights for read alien messages.',403);
			$this->_response->setException($oException);
			return;
		}

		// Формирование объекта таблицы JQueryGrid.
		$this->view->jqgrid = $this->view->JQueryGrid()
			->setTableId('MessagesList')
			->setPagerId('MessagesListPager')
			->setOptions(array(
			//	'caption' => 'Список пользователей',
				'url' => '/users/admin/list-message-model',
				'mtype' => 'POST',
				'colNames' => array_keys($this->_aMessageListColumns),
				'colModel' => array_values($this->_aMessageListColumns),
				'sortname' => 'created',
				'multiselect' => true,
				'editurl' => '/users/admin/ajax-message-operations',
			))
       		->enableNavGrid(array(
            	'add' => false,
	            'edit' => false,
    	    ));
	}

	/**
	 * Получение данных для таблицы списка личных сообщений пользователей.
	 */
	public function listMessageModelAction() {
		$aFilter = array();

		// Получение запрашиваемого списка пользователей.
		foreach ($this->_getList('Users_Model_Message',$aFilter,$this->_aMessageListColumns,$oResponce) as $oMessage) {
			$oResponce->rows[] = array(
				'id' => 'm'.$oMessage->getId(),
				'cell' => array(
					$this->view->ClientDateTime($oMessage->getCreated(),'d.m.Y H:i')->direct(),
					$oMessage->getSubject(),
					(0 < $iTarget = intval($oMessage->getTarget()))
						?( ($sFullName = trim(join(' ',array(
							Users_Model_User::getById($iTarget)->getLastName(),
							Users_Model_User::getById($iTarget)->getFirstName(),
							Users_Model_User::getById($iTarget)->getPatronymic(),
						))))
							? $sFullName
							: Users_Model_User::getById($iTarget)->getLogin()
						): '<i>Всем пользователям</i>',
					(0 < $iTarget = intval($oMessage->getCreatedBy()))
						?( ($sFullName = trim(join(' ',array(
							Users_Model_User::getById($iTarget)->getLastName(),
							Users_Model_User::getById($iTarget)->getFirstName(),
							Users_Model_User::getById($iTarget)->getPatronymic(),
						))))
							? $sFullName
							: Users_Model_User::getById($iTarget)->getLogin()
						): '<i>неизвестного</i>',
				),
			);
		}

		// Вывод данных для ответа на AJAX запрос.
		$this->_helper->json($oResponce,true);
	}

	/**
	 * Переадрессация на страницу со списком групп доступа.
	 */
	public function aclManagerAction() {
		try {
			$this->_response->setRedirect('/users/admin/list-resource',302);
		}
		catch (Exception $e) {
			$this->_setParam('show_error', true);
			$this->_response->setException($e);
		}
	}

    public function listResourceAction() {

        $this->view->jqgrid = $this->view->JQueryGrid()
                ->setTableId('resourceList')
                ->setPagerId('resourcePager')
                ->setOptions(array(
                    'caption' => $this->_actionConfig['jqgrid_resource_caption'],
                    'url' => $this->_helper->url('list-resource-model'),
                    'mtype' => 'GET',
                    'colNames' => array_values($this->_actionConfig['jqgrid_resource_col_names']),
                    'colModel' => array_values($this->_actionConfig['jqgrid_resource_col_model']),
                    'sortname' => 'id',
                    'sortorder' => "desc",
                    'viewrecords' => true,
                    'multiselect' => true,
                    'editurl'   => $this->_helper->url('ajax-resource-operations'),
                    'autowidth' => true,
                    'rowNum' => 20,
                    'subGrid' => true,
                    'subGridRowExpanded' => new Zend_Json_Expr($this->_helper->application->jsFunction('expand', array('subgrid_id', 'row_id'), true)),
                ))
                ->enableNavGrid(array(
                    'add' => true,
                    'del' => true,
                    'edit' => true,
					'search' => true
                ));

        $this->view->subjqgrid = $this->view->JQueryGrid()->getNewInstance()
                ->setTableId('privilegeList')
                ->setPagerId('privilegePager')
                ->setOptions(array(
                    'url' => $this->_helper->url('list-privilege-model'),
                    'mtype' => 'GET',
                    'colNames' => array_values($this->_actionConfig['jqgrid_privilege_col_names']),
                    'colModel' => array_values($this->_actionConfig['jqgrid_privilege_col_model']),
                    'sortname' => 'id',
                    'sortorder' => "desc",
                    'viewrecords' => true,
                    'multiselect' => true,
                    'editurl'   => $this->_helper->url('ajax-resource-privilege-operations'),
                    'width' => '500px',
                    'autowidth' => false,
                    'rowNum' => 20,
                ))
                ->enableNavGrid(array(
                    'add' => false,
                    'del' => true,
                    'edit' => false,
                ));


        $this->view->jqgrid->jsObject = $this->_helper->application->jsFunctionName();
    }

    public function listResourceModelAction() {

        $page = (int)$this->_getParam('page');
        if ($page < 1) {
           $page = 1;
        }

        $rows = (int)$this->_getParam('rows');
        if ($rows < 1) {
            $rows = Workset_Model_Object_Abstract::ROWS_LIMIT;
        }

        $cols = $this->_helper->application->getList('cols', true);

        $order = $this->_helper->application->getSortOrder();

		$filter = $this->_getParam('filters');
		$filter = $this->_helper->JQueryGrid->getFilter($filter, $this->_actionConfig['jqgrid_resource_col_model']);

        $colNames = $this->_helper->utils->arrayValues(
            $this->_actionConfig['jqgrid_resource_col_model'], 'index', 1
        );

        if ($cols) {
            $cols = array_intersect($colNames, $cols);
        } else {
            $cols = $colNames;
        }

        $storage = new Users_Model_Access_Resource_Storage_Table();

        $items = $storage->getAll($filter, $order, $rows, $page, true);

        $records = $this->_helper->JQueryGrid(
            $items, $page, ceil($items->getTotalCount() / $rows),
            $items->getTotalCount(), $cols
        );

        $this->_helper->json($records, true);

    }

    public function ajaxResourceOperationsAction() {
        $this->_helper->viewRenderer->setNoRender(true);

        $actionSwitcher = new Workset_Controller_Plugin_ActionSwitcher('oper', array(
            'del' => array(
                'action' => 'delete-resource',
            ),
            'edit' => array(
                'action' => 'edit-resource'
            ),
            'add' => array(
                'action' => 'add-resource'
            ),
        ));

        $this->getFrontController()->registerPlugin($actionSwitcher, 1);
        $this->_setParam('handlePostDispatch', false);
    }

    public function addResourceAction() {
        $type = 'resource';
        $oper = $this->_getParam('oper');
        $outerEdit = !empty($oper) && $this->_request->isXmlHttpRequest() ? true : false;

        if ($outerEdit) {
            $this->_helper->viewRenderer->setNoRender(true);
        }

        $formConfig = $this->_helper->moduleConfig('forms/'.$type);
        $form = new Workset_Form($formConfig);

        //транслятор формы
        $form->setTranslator(
            $this->_translate,
            $this->_helper->moduleConfig->getConfig(array('lang', $this->_locale, 'validators'), null, true)
        );

        if ($this->_request->isPost()) {
            try {
                $post = $this->_request->getPost();

                //редактирование через внешнюю форму (jqGrid)
                if ($outerEdit) {
                    $post = $this->_helper->utils->addPrefix($post, $type);
                }

                if ($form->isValid($post)) {
                    $values = $form->getValues();
                    $values = $this->_helper->utils->stripPrefix($values, $type);

                    $storage = new Users_Model_Access_Resource_Storage_Table();
                    $object = $storage->create($values);

					if (!empty($this->_actionConfig['default_privileges'])) {
						$privilegeStorage = new Users_Model_Access_Privilege_Storage_Table();
						$privileges = $privilegeStorage->getAll(array(
                            'code in(?)' => $this->_actionConfig['default_privileges'],
                        ));

						foreach ($privileges as $p) {
							$object->addPrivilege($p);
						}
					}

                    $object->save();

                    if (!$this->_request->isXmlHttpRequest()) {
                        $this->_helper->redirector->gotoSimple('list-'.$type);
                    } else {
                        return;
                    }
                }

                throw new Workset_Model_Exception($form->getCustomMessages(Workset_Form::ERROR_CODE), Workset_Form::ERROR_CODE);

            } catch (Zend_Exception $e) {
                $this->_helper->application->throwException($e, null, false);
            }
        }

        $backToListUrl = $this->_helper->url('list-'.$type);

        $this->view->form = $form;
        $this->view->backurl = $backToListUrl;
    }

    public function editResourceAction() {
        $type = 'resource';
        $id = (int)$this->_getParam('id');

        $storage = new Users_Model_Access_Resource_Storage_Table();
        $object = $storage->getOne($id);

        $oper = $this->_getParam('oper');
        $outerEdit = !empty($oper) && $this->_request->isXmlHttpRequest() ? true : false;

        if ($outerEdit) {
            $this->_helper->viewRenderer->setNoRender(true);
        }

        $formConfig = $this->_helper->moduleConfig('forms/'.$type);
        $form = new Workset_Form($formConfig);

        // Транслятор формы
        $form->setTranslator(
            $this->_translate,
            $this->_helper->moduleConfig->getConfig(array('lang', $this->_locale, 'validators'), null, true)
        );

        if ($this->_request->isPost()) {
            try {
                $post = $this->_request->getPost();

                // Редактирование через внешнюю форму (jqGrid)
                if ($outerEdit) {
                    $post = $this->_helper->utils->addPrefix($post, $type);
                }

                if ($form->isValid($post)) {
                    $values = $form->getValues();
                    $values = $this->_helper->utils->stripPrefix($values, $type);

                    $object->setData($values);
                    $object->save();

                    if (!$this->_request->isXmlHttpRequest()) {
                        $this->_helper->redirector->gotoSimple('list-'.$type);
                    } else {
                        return;
                    }
                }

                throw new Workset_Model_Exception($form->getCustomMessages(Workset_Form::ERROR_CODE), Workset_Form::ERROR_CODE);

            } catch (Zend_Exception $e) {
                $this->_helper->application->throwException($e, null, false);
            }
        } else {
            foreach ($object->toArray() as $key => $value) {
                $key = $type.'_'.$key;
                if ($element = $form->getElement($key)) {
                    $element->setValue($value);
                }
            }
        }

        $this->view->form = $form;
        $this->render('add-'.$type);
    }

    public function deleteResourceAction() {
        $type = 'resource';
        $this->_helper->viewRenderer->setNoRender(true);

        $listId = $this->_helper->application->getListId('id', true);

        if (empty($listId)) {
            throw $this->_helper->application->throwException(null, 404);
        }

        $filter = array('id in(?)' => $listId);

        $storage = new Users_Model_Access_Resource_Storage_Table();
        $items = $storage->getAll($filter);

        try {
            foreach ($items as $object) {
                $object->delete();
            }
        } catch (Zend_Exception $e) {
            $this->_helper->application->throwException($e);
        }

        if (!$this->_request->isXmlHttpRequest()) {
            $redirect = $this->_helper->url('list-'.$type);
            $this->_redirect($redirect);
        }
    }

    public function ajaxResourcePrivilegeOperationsAction() {
        $this->_helper->viewRenderer->setNoRender(true);

        $actionSwitcher = new Workset_Controller_Plugin_ActionSwitcher('oper', array(
            'del' => array(
                'action' => 'delete-resource-privilege',
            ),
            'add' => array(
                'action' => 'add-resource-privilege'
            ),
        ));

        $this->getFrontController()->registerPlugin($actionSwitcher, 1);
        $this->_setParam('handlePostDispatch', false);
    }

    public function addResourcePrivilegeAction() {
		$type = 'resource';
        $this->_helper->viewRenderer->setNoRender(true);

		$resourceId = (int)$this->_getParam('nodeid');
		$privilegeId = (int)$this->_getParam('id');

		if ($resourceId < 1 || $privilegeId < 1) {
			throw $this->_helper->application->throwException(null, 404);
		}

		$resourceStorage = new Users_Model_Access_Resource_Storage_Table();
        $privilegeStorage = new Users_Model_Access_Privilege_Storage_Table();

        $resource = $resourceStorage->getOne($resourceId);
        $privilege = $privilegeStorage->getOne($privilegeId);
		$privileges = $privilegeStorage->getAllByResource($resource, array('id = ?' => $privilegeId));

		if ($privileges->count() > 0) {
			throw $this->_helper->application->throwException(null, 404);
		}

		try {
            $resource->addPrivilege($privilege)->save();
        } catch (Zend_Exception $e) {
            $this->_helper->application->throwException($e);
        }

        if (!$this->_request->isXmlHttpRequest()) {
            $redirect = $this->_helper->url('list-'.$type);
            $this->_redirect($redirect);
        }
    }

    public function deleteResourcePrivilegeAction() {
        $type = 'resource';
        $this->_helper->viewRenderer->setNoRender(true);

        $resourceId = (int)$this->_getParam('nodeid');
        $listId = $this->_helper->application->getListId('id', true);

        if (empty($listId)) {
            throw $this->_helper->application->throwException(null, 404);
        }

        $resourceStorage = new Users_Model_Access_Resource_Storage_Table();
        $privilegeStorage = new Users_Model_Access_Privilege_Storage_Table();

        $resource = $resourceStorage->getOne($resourceId);
        $privileges = $privilegeStorage->getAll(array('id in(?)' => $listId));

        foreach ($privileges as $p) {
            $resource->deletePrivilege($p);
        }

        try {
            $resource->save();
        } catch (Zend_Exception $e) {
            $this->_helper->application->throwException($e);
        }

        if (!$this->_request->isXmlHttpRequest()) {
            $redirect = $this->_helper->url('list-'.$type);
            $this->_redirect($redirect);
        }
    }

	public function listPrivilegeAction() {
        $this->view->jqgrid = $this->view->JQueryGrid()
                ->setTableId('privilegeList')
                ->setPagerId('privilegePager')
                ->setOptions(array(
                    'caption' => $this->_actionConfig['jqgrid_privilege_caption'],
                    'url' => $this->_helper->url('list-privilege-model'),
                    'mtype' => 'GET',
                    'colNames' => array_values($this->_actionConfig['jqgrid_privilege_col_names']),
                    'colModel' => array_values($this->_actionConfig['jqgrid_privilege_col_model']),
                    'sortname' => 'id',
                    'sortorder' => "desc",
                    'viewrecords' => true,
                    'multiselect' => true,
                    'editurl'   => $this->_helper->url('ajax-privilege-operations'),
                    'autowidth' => true,
                    'rowNum' => 20,
                ))
                ->enableNavGrid(array(
                    'add' => true,
                    'del' => true,
                    'edit' => true,
					'search' => true
                ));
	}

	public function listPrivilegeModelAction() {
        $resourceId = (int)$this->_getParam('id');
        $diff = (int)$this->_getParam('diff');

		$page = (int)$this->_getParam('page');
		if ($page < 1) {
		   $page = 1;
		}

		$rows = (int)$this->_getParam('rows');
		if ($rows < 1) {
			$rows = Workset_Model_Object_Abstract::ROWS_LIMIT;
		}

		$cols = $this->_helper->application->getList('cols', true);

		$order = $this->_helper->application->getSortOrder();

		$filter = $this->_getParam('filters');
		$filter = $this->_helper->JQueryGrid->getFilter($filter, $this->_actionConfig['jqgrid_privilege_col_model']);

		$colNames = $this->_helper->utils->arrayValues(
			$this->_actionConfig['jqgrid_privilege_col_model'], 'index', 1
		);

		if ($cols) {
			$cols = array_intersect($colNames, $cols);
		} else {
			$cols = $colNames;
		}

		$storage = new Users_Model_Access_Privilege_Storage_Table();

        if ($resourceId > 0) {
            $resourceStorage = new Users_Model_Access_Resource_Storage_Table();
            $resource = $resourceStorage->getOne($resourceId);
            $items = $storage->getAllByResource($resource, $filter, $order, $rows, $page, true);

        } elseif ($diff > 0) {
            $resourceStorage = new Users_Model_Access_Resource_Storage_Table();
            $resource = $resourceStorage->getOne($diff);
            $items = $storage->getAvailablePrivileges($resource, $filter, $order, $rows, $page, true);
        } else {
            $items = $storage->getAll($filter, $order, $rows, $page, true);
        }

		$records = $this->_helper->JQueryGrid(
			$items, $page, ceil($items->getTotalCount() / $rows),
			$items->getTotalCount(), $cols
		);

		$this->_helper->json($records, true);
	}

	public function ajaxPrivilegeOperationsAction() {
        $this->_helper->viewRenderer->setNoRender(true);

        $actionSwitcher = new Workset_Controller_Plugin_ActionSwitcher('oper', array(
            'del' => array(
                'action' => 'delete-privilege',
            ),
            'edit' => array(
                'action' => 'edit-privilege'
            ),
            'add' => array(
                'action' => 'add-privilege'
            ),
        ));

        $this->getFrontController()->registerPlugin($actionSwitcher, 1);
        $this->_setParam('handlePostDispatch', false);
	}

	public function addPrivilegeAction() {
		$type = 'privilege';
        $oper = $this->_getParam('oper');
        $outerEdit = !empty($oper) && $this->_request->isXmlHttpRequest() ? true : false;

        if ($outerEdit) {
            $this->_helper->viewRenderer->setNoRender(true);
        }

        $formConfig = $this->_helper->moduleConfig('forms/'.$type);
        $form = new Workset_Form($formConfig);

        //транслятор формы
        $form->setTranslator(
            $this->_translate,
            $this->_helper->moduleConfig->getConfig(array('lang', $this->_locale, 'validators'), null, true)
        );

        if ($this->_request->isPost()) {
            try {
                $post = $this->_request->getPost();

                //редактирование через внешнюю форму (jqGrid)
                if ($outerEdit) {
                    $post = $this->_helper->utils->addPrefix($post, $type);
                }

                if ($form->isValid($post)) {
                    $values = $form->getValues();
                    $values = $this->_helper->utils->stripPrefix($values, $type);

                    $storage = new Users_Model_Access_Privilege_Storage_Table();
                    $object = $storage->create($values);
                    $object->save();

                    if (!$this->_request->isXmlHttpRequest()) {
                        $this->_helper->redirector->gotoSimple('list-'.$type);
                    } else {
                        return;
                    }
                }

                throw new Workset_Model_Exception($form->getCustomMessages(Workset_Form::ERROR_CODE), Workset_Form::ERROR_CODE);

            } catch (Zend_Exception $e) {
                $this->_helper->application->throwException($e, null, false);
            }
        }

        $backToListUrl = $this->_helper->url('list-'.$type);

        $this->view->form = $form;
        $this->view->backurl = $backToListUrl;
	}

	public function editPrivilegeAction() {
		$type = 'privilege';
        $id = (int)$this->_getParam('id');

        $storage = new Users_Model_Access_Privilege_Storage_Table();
        $object = $storage->getOne($id);

        $oper = $this->_getParam('oper');
        $outerEdit = !empty($oper) && $this->_request->isXmlHttpRequest() ? true : false;

        if ($outerEdit) {
            $this->_helper->viewRenderer->setNoRender(true);
        }

        $formConfig = $this->_helper->moduleConfig('forms/'.$type);
        $form = new Workset_Form($formConfig);

        //транслятор формы
        $form->setTranslator(
            $this->_translate,
            $this->_helper->moduleConfig->getConfig(array('lang', $this->_locale, 'validators'), null, true)
        );

        if ($this->_request->isPost()) {
            try {
                $post = $this->_request->getPost();

                //редактирование через внешнбб форму (jqGrid)
                if ($outerEdit) {
                    $post = $this->_helper->utils->addPrefix($post, $type);
                }

                if ($form->isValid($post)) {
                    $values = $form->getValues();
                    $values = $this->_helper->utils->stripPrefix($values, $type);

                    $object->setData($values);
                    $object->save();

                    if (!$this->_request->isXmlHttpRequest()) {
                        $this->_helper->redirector->gotoSimple('list-'.$type);
                    } else {
                        return;
                    }
                }

                throw new Workset_Model_Exception($form->getCustomMessages(Workset_Form::ERROR_CODE), Workset_Form::ERROR_CODE);

            } catch (Zend_Exception $e) {
                $this->_helper->application->throwException($e, null, false);
            }
        } else {
            foreach ($object->toArray() as $key => $value) {
                $key = $type.'_'.$key;
                if ($element = $form->getElement($key)) {
                    $element->setValue($value);
                }
            }
        }

        $this->view->form = $form;
        $this->render('add-'.$type);
	}

	public function deletePrivilegeAction() {
		$type = 'privilege';
        $this->_helper->viewRenderer->setNoRender(true);

        $listId = $this->_helper->application->getListId('id', true);

        if (empty($listId)) {
            throw $this->_helper->application->throwException(null, 404);
        }

        $filter = array('id in(?)' => $listId);

        $storage = new Users_Model_Access_Privilege_Storage_Table();
        $items = $storage->getAll($filter);

        try {
            foreach ($items as $object) {
                $object->delete();
            }
        } catch (Zend_Exception $e) {
            $this->_helper->application->throwException($e);
        }

        if (!$this->_request->isXmlHttpRequest()) {
            $redirect = $this->_helper->url('list-'.$type);
            $this->_redirect($redirect);
        }
	}

    public function listRoleAction() {

        $this->view->jqgrid = $this->view->JQueryGrid()
                ->setTableId('roleList')
                ->setPagerId('rolePager')
                ->setOptions(array(
                    'caption' => $this->_actionConfig['jqgrid_role_caption'],
                    'url' => $this->_helper->url('list-role-model'),
                    'mtype' => 'GET',
                    'colNames' => array_values($this->_actionConfig['jqgrid_role_col_names']),
                    'colModel' => array_values($this->_actionConfig['jqgrid_role_col_model']),
                    'sortname' => 'id',
                    'sortorder' => "desc",
                    'viewrecords' => true,
                    'multiselect' => true,
                    'editurl'   => $this->_helper->url('ajax-role-operations'),
                    'autowidth' => true,
                    'rowNum' => 20,
					'ondblClickRow' => new Zend_Json_Expr(
						$this->_helper->application->jsFunction('roleInfo', array('rowId', 'url' => $this->_helper->url('ajax-role-operations')), true)
					)
                ))
                ->enableNavGrid(array(
                    'add' => true,
                    'del' => true,
                    'edit' => true,
					'search' => true
                ))
				->addNavButton('b_view', array(
                    'buttonicon' => 'ui-icon-document',
                    'caption' => 'Настройки роли',
                    'position' => 'last',
                    'onClickButton' => new Zend_Json_Expr(
						$this->_helper->application->jsFunction('roleInfo', array('rowId' => null, 'url' => $this->_helper->url('ajax-role-operations')), true)
					)
                ))
                ->addNavButton('b_group', array(
                    'buttonicon' => 'ui-icon-document',
                    'caption' => 'Группы доступа',
                    'position' => 'last',
                    'onClickButton' => new Zend_Json_Expr(
						$this->_helper->application->jsFunction('roleGroup', array('rowId' => null, 'url' => $this->_helper->url('ajax-role-operations')), true)
					)
                ));

		$this->view->jqgrid->jsObject = $this->_helper->application->jsFunctionName();
    }

    public function listRoleModelAction() {

        $page = (int)$this->_getParam('page');
        if ($page < 1) {
           $page = 1;
        }

        $rows = (int)$this->_getParam('rows');
        if ($rows < 1) {
            $rows = Workset_Model_Object_Abstract::ROWS_LIMIT;
        }

        $cols = $this->_helper->application->getList('cols', true);

        $order = $this->_helper->application->getSortOrder();

		$filter = $this->_getParam('filters');
		$filter = $this->_helper->JQueryGrid->getFilter($filter, $this->_actionConfig['jqgrid_role_col_model']);

        $colNames = $this->_helper->utils->arrayValues(
            $this->_actionConfig['jqgrid_role_col_model'], 'index', 1
        );

        if ($cols) {
            $cols = array_intersect($colNames, $cols);
        } else {
            $cols = $colNames;
        }

        $storage = new Users_Model_Access_Role_Storage_Table();

        $items = $storage->getAll($filter, $order, $rows, $page, true);

        $records = $this->_helper->JQueryGrid(
            $items, $page, ceil($items->getTotalCount() / $rows),
            $items->getTotalCount(), $cols
        );

        $this->_helper->json($records, true);
    }

    public function ajaxRoleOperationsAction() {
        $this->_helper->viewRenderer->setNoRender(true);

        $actionSwitcher = new Workset_Controller_Plugin_ActionSwitcher('oper', array(
            'del' => array(
                'action' => 'delete-role',
            ),
            'edit' => array(
                'action' => 'edit-role'
            ),
            'add' => array(
                'action' => 'add-role'
            ),
            'view' => array(
                'action' => 'view-role',
                'params' => array(
                    'id' => $this->_getParam('id')
                )
            ),
           'group' => array(
                'action' => 'list-role-group',
                'params' => array(
                    'id' => $this->_getParam('id')
                )
            ),
        ));

        $this->getFrontController()->registerPlugin($actionSwitcher, 1);
        $this->_setParam('handlePostDispatch', false);
    }

    public function viewRoleAction() {
        $roleId = (int)$this->_getParam('id');
        $storageRole = new Users_Model_Access_Role_Storage_Table();
        $role = $storageRole->getOne($roleId);

        $this->_addNavItem(array(
            'label' => $role['name'],
            'title' => $role['name'],
            'id' => $role['code'],
            'params' => array('id' => $role->getId())
        ));

        $this->_layoutPageTitle = implode($this->_actionConfig['title_part_sep'], array(
            $this->_actionConfig['title'],
            $role['name'],
        ));

        //текущие правила доступа
        $rules = $role->getRules()->toArray(array(
            'resource_id',
            'privilege_id'
        ));

        $this->view->jqgrid = $this->view->JQueryGrid()
                ->setTableId('resourceList')
                ->setPagerId('resourcePager')
                ->setOptions(array(
                    'caption' => $this->_actionConfig['jqgrid_role_caption'],
                    'url' => $this->_helper->url('list-resource-model', null, null, array(
						'filters' => array('status = ?' => Users_Model_Access_Resource::HAS_PRIVILEGES)
					)),
                    'mtype' => 'GET',
                    'colNames' => array_values($this->_actionConfig['jqgrid_resource_col_names']),
                    'colModel' => array_values($this->_actionConfig['jqgrid_resource_col_model']),
                    'sortname' => 'id',
                    'sortorder' => "desc",
                    'viewrecords' => true,
                    'multiselect' => true,
                    'autowidth' => true,
                    'rowNum' => 20,
                    'subGrid' => true,
                    'subGridRowExpanded' => new Zend_Json_Expr($this->_helper->application->jsFunction('subGridRowExpanded', array('subgrid_id', 'row_id'), true)),
                    'subGridRowColapsed' => new Zend_Json_Expr($this->_helper->application->jsFunction('subGridRowColapsed', array('subgrid_id', 'row_id'), true)),
                    'onSelectRow' => new Zend_Json_Expr($this->_helper->application->jsFunction('onSelectRow', array('rowId', 'status'), true)),
					'onSelectAll' => new Zend_Json_Expr($this->_helper->application->jsFunction('onSelectAll', array('rowIds', 'status'), true)),
					'gridComplete' => new Zend_Json_Expr($this->_helper->application->jsFunction('gridComplete', array('settings' => array(
                        'roleId' => $role->getId(),
                        'saveUrl' => $this->_helper->url('set-rules'),
                        'deleteUrl' => $this->_helper->url('delete-rule'),
                        'backUrl' => $this->_helper->url('list-role'),
                        'rules' => $rules,
                        'rulesFormat' => array('resource' => 0, 'privilege' => 1)
                    )), true)),
                ))
                ->enableNavGrid(array(
                    'add' => false,
                    'del' => false,
                    'edit' => false,
                    'refresh' => false
                ))
                ->addNavButton('b_view', array(
                    'buttonicon' => 'ui-icon-circle-check',
                    'caption' => 'Сохранить',
                    'position' => 'first',
                    'onClickButton' => new Zend_Json_Expr(
						$this->_helper->application->jsFunction('saveResources', null, true)
					)
                ))
                ->addNavButton('b_back', array(
                    'buttonicon' => 'ui-icon-circle-arrow-w',
                    'caption' => 'Выйти',
                    'position' => 'first',
                    'onClickButton' => new Zend_Json_Expr(
						$this->_helper->application->jsFunction('comeback', null, true)
					)
                ));

        $this->view->subjqgrid = $this->view->JQueryGrid()->getNewInstance()
                ->setTableId('privilegeList')
                ->setPagerId('privilegePager')
                ->setOptions(array(
                    'url' => $this->_helper->url('list-privilege-model'),
                    'mtype' => 'GET',
                    'colNames' => array_values($this->_actionConfig['jqgrid_privilege_col_names']),
                    'colModel' => array_values($this->_actionConfig['jqgrid_privilege_col_model']),
                    'sortname' => 'id',
                    'sortorder' => "desc",
                    'viewrecords' => true,
                    'multiselect' => true,
                    'width' => '500px',
                    'autowidth' => false,
                    'rowNum' => 0,
                ));

        $this->view->jqgrid->jsObject = $this->_helper->application->jsFunctionName();
    }

    public function listRoleGroupAction() {
        $roleId = (int)$this->_getParam('id');

        $roleStorage = new Users_Model_Access_Role_Storage_Table();

        $role = $roleStorage->getOne($roleId);
        $groups = $role->getGroups()->toArray('id');

		$this->_addNavItem(array(
            'label' => $role['name'],
            'title' => $role['name'],
            'id' => $role['code'],
            'params' => array('id' => $role->getId())
        ));

        $this->view->jqgrid = $this->view->JQueryGrid()
                ->setTableId('groupList1')
                ->setPagerId('groupPager1')
                ->setOptions(array(
                    'caption' => $this->_actionConfig['jqgrid_group_caption'],
                    'url' => $this->_helper->url('list-group-model', null, null, array('diff' => $groups)),
                    'mtype' => 'GET',
                    'colNames' => array_values($this->_actionConfig['jqgrid_group_col_names']),
                    'colModel' => array_values($this->_actionConfig['jqgrid_group_col_model']),
                    'sortname' => 'id',
                    'sortorder' => "desc",
                    'viewrecords' => true,
                    'editurl'   => $this->_helper->url('ajax-group-operations'),
                    'autowidth' => false,
                    'rowNum' => 20,
                    'width' => 400
                ))
                ->invokeParams(array(
					'nodeid' => $role->getId(),
					'url' => $this->_helper->url('add-role-group')
				))
				->addMethod('gridDnD', array(
					'connectWith' => '#groupList2',
					'ondrop' => new Zend_Json_Expr(
						$this->_helper->application->jsFunction(
							'addItem',
							array('evt', 'context'),
							true
						)
					),
				))
				->gridComplete(false);

        $this->view->selectedjqgrid = $this->view->JQueryGrid()->getNewInstance()
                ->setTableId('groupList2')
                ->setPagerId('groupPager2')
                ->setOptions(array(
                    'caption' => $this->_actionConfig['jqgrid_selected_group_caption'],
                    'datatype' => $groups ? 'json' : 'local',
                    'url' => $this->_helper->url('list-group-model', null, null, array('intersect' => $groups)),
                    'mtype' => 'GET',
                    'colNames' => array_values($this->_actionConfig['jqgrid_group_col_names']),
                    'colModel' => array_values($this->_actionConfig['jqgrid_group_col_model']),
                    'sortname' => 'id',
                    'sortorder' => "desc",
                    'viewrecords' => true,
                    'editurl'   => $this->_helper->url('ajax-group-operations'),
                    'autowidth' => false,
                    'rowNum' => 20,
                    'width' => 400
                ))
                ->invokeParams(array(
                    'nodeid' => $role->getId(),
                    'url' => $this->_helper->url('delete-role-group')
                ))
                ->addMethod('gridDnD', array(
                    'connectWith' => '#groupList1',
                    'ondrop' => new Zend_Json_Expr(
                        $this->_helper->application->jsFunction(
                            'removeItem',
                            array('evt', 'context'),
                            true
                        )
                    ),
                ))
                ->gridComplete(false);

		$this->view->jsObject = $this->_helper->application->jsFunctionName();
        $this->view->backurl = $this->_helper->url('list-role');
        $this->view->backurlLabel = $this->_actionConfig['backurl_label'];

        $this->render('select-group');
    }

    public function addRoleAction() {
        $type = 'role';
        $oper = $this->_getParam('oper');
        $outerEdit = !empty($oper) && $this->_request->isXmlHttpRequest() ? true : false;

        if ($outerEdit) {
            $this->_helper->viewRenderer->setNoRender(true);
        }

        $formConfig = $this->_helper->moduleConfig('forms/'.$type);
        $form = new Workset_Form($formConfig);

        //транслятор формы
        $form->setTranslator(
            $this->_translate,
            $this->_helper->moduleConfig->getConfig(array('lang', $this->_locale, 'validators'), null, true)
        );

        if ($this->_request->isPost()) {
            try {
                $post = $this->_request->getPost();

                //редактирование через внешнюю форму (jqGrid)
                if ($outerEdit) {
                    $post = $this->_helper->utils->addPrefix($post, $type);
                }

                if ($form->isValid($post)) {
                    $values = $form->getValues();
                    $values = $this->_helper->utils->stripPrefix($values, $type);

                    $storage = new Users_Model_Access_Role_Storage_Table();
                    $object = $storage->create($values);
                    $object->save();

                    if (!$this->_request->isXmlHttpRequest()) {
                        $this->_helper->redirector->gotoSimple('list-'.$type);
                    } else {
                        return;
                    }
                }

                throw new Workset_Model_Exception($form->getCustomMessages(Workset_Form::ERROR_CODE), Workset_Form::ERROR_CODE);

            } catch (Zend_Exception $e) {
                $this->_helper->application->throwException($e, null, false);
            }
        }

        $backToListUrl = $this->_helper->url('list-'.$type);

        $this->view->form = $form;
        $this->view->backurl = $backToListUrl;
    }

    public function editRoleAction() {
        $type = 'role';
        $id = (int)$this->_getParam('id');

        $storage = new Users_Model_Access_Role_Storage_Table();
        $object = $storage->getOne($id);

        $oper = $this->_getParam('oper');
        $outerEdit = !empty($oper) && $this->_request->isXmlHttpRequest() ? true : false;

        if ($outerEdit) {
            $this->_helper->viewRenderer->setNoRender(true);
        }

        $formConfig = $this->_helper->moduleConfig('forms/'.$type);
        $form = new Workset_Form($formConfig);

        //транслятор формы
        $form->setTranslator(
            $this->_translate,
            $this->_helper->moduleConfig->getConfig(array('lang', $this->_locale, 'validators'), null, true)
        );

        if ($this->_request->isPost()) {
            try {
                $post = $this->_request->getPost();

                //редактирование через внешнбб форму (jqGrid)
                if ($outerEdit) {
                    $post = $this->_helper->utils->addPrefix($post, $type);
                }

                if ($form->isValid($post)) {
                    $values = $form->getValues();
                    $values = $this->_helper->utils->stripPrefix($values, $type);

                    $object->setData($values);
                    $object->save();

                    if (!$this->_request->isXmlHttpRequest()) {
                        $this->_helper->redirector->gotoSimple('list-'.$type);
                    } else {
                        return;
                    }
                }

                throw new Workset_Model_Exception($form->getCustomMessages(Workset_Form::ERROR_CODE), Workset_Form::ERROR_CODE);

            } catch (Zend_Exception $e) {
                $this->_helper->application->throwException($e, null, false);
            }
        } else {
            foreach ($object->toArray() as $key => $value) {
                $key = $type.'_'.$key;
                if ($element = $form->getElement($key)) {
                    $element->setValue($value);
                }
            }
        }

		$this->view->backurl = $this->_helper->url('list-'.$type);
        $this->view->form = $form;
        $this->render('add-'.$type);
    }

    public function deleteRoleAction() {
 		$type = 'role';
        $this->_helper->viewRenderer->setNoRender(true);

        $listId = $this->_helper->application->getListId('id', true);

        if (empty($listId)) {
            throw $this->_helper->application->throwException(null, 404);
        }

        $filter = array('id in(?)' => $listId);

        $storage = new Users_Model_Access_Role_Storage_Table();
        $items = $storage->getAll($filter);

        try {
            foreach ($items as $object) {
                $object->delete();
            }
        } catch (Zend_Exception $e) {
            $this->_helper->application->throwException($e);
        }

        if (!$this->_request->isXmlHttpRequest()) {
            $redirect = $this->_helper->url('list-'.$type);
            $this->_redirect($redirect);
        }
    }

    public function listGroupAction() {
        $this->view->jqgrid = $this->view->JQueryGrid()
                ->setTableId('groupList')
                ->setPagerId('groupPager')
                ->setOptions(array(
                    'caption' => $this->_actionConfig['jqgrid_group_caption'],
                    'url' => $this->_helper->url('list-group-model'),
                    'mtype' => 'GET',
                    'colNames' => array_values($this->_actionConfig['jqgrid_group_col_names']),
                    'colModel' => array_values($this->_actionConfig['jqgrid_group_col_model']),
                    'sortname' => 'id',
                    'sortorder' => "desc",
                    'viewrecords' => true,
                    'multiselect' => true,
                    'editurl'   => $this->_helper->url('ajax-group-operations'),
                    'autowidth' => true,
                    'rowNum' => 20,
                ))
                ->enableNavGrid(array(
                    'add' => true,
                    'del' => true,
                    'edit' => true,
					'search' => true
                ));

		$this->view->jqgrid->jsObject = $this->_helper->application->jsFunctionName();
    }

    public function listGroupModelAction() {
        //выбирать только несовпадающие элементы
        $diff = $this->_getParam('diff');
        if ($diff) {
            $diff = $this->_helper->application->getListId($diff);
        }

        //выбирать только совпадающие элементы
        $intersect = $this->_getParam('intersect');
        if ($intersect) {
            $intersect = $this->_helper->application->getListId($intersect);
        }

        $page = (int)$this->_getParam('page');
        if ($page < 1) {
           $page = 1;
        }

        $rows = (int)$this->_getParam('rows');
        if ($rows < 1) {
            $rows = Workset_Model_Object_Abstract::ROWS_LIMIT;
        }

        $cols = $this->_helper->application->getList('cols', true);

        $order = $this->_helper->application->getSortOrder();

		$filter = $this->_getParam('filters');
		$filter = $this->_helper->JQueryGrid->getFilter($filter, $this->_actionConfig['jqgrid_group_col_model']);

        if ($diff) {
            $filter['id not in(?)'] = $diff;
        }

        if ($intersect) {
            $filter['id in(?)'] = $intersect;
        }

        $colNames = $this->_helper->utils->arrayValues(
            $this->_actionConfig['jqgrid_group_col_model'], 'index', 1
        );

        if ($cols) {
            $cols = array_intersect($colNames, $cols);
        } else {
            $cols = $colNames;
        }

        $storage = new Users_Model_Access_Group_Storage_Table();

        $items = $storage->getAll($filter, $order, $rows, $page, true);

        $records = $this->_helper->JQueryGrid(
            $items, $page, ceil($items->getTotalCount() / $rows),
            $items->getTotalCount(), $cols
        );

        $this->_helper->json($records, true);
    }

    public function ajaxGroupOperationsAction() {
        $this->_helper->viewRenderer->setNoRender(true);

        $actionSwitcher = new Workset_Controller_Plugin_ActionSwitcher('oper', array(
            'del' => array(
                'action' => 'delete-group',
            ),
            'edit' => array(
                'action' => 'edit-group'
            ),
            'add' => array(
                'action' => 'add-group'
            ),
        ));

        $this->getFrontController()->registerPlugin($actionSwitcher, 1);
        $this->_setParam('handlePostDispatch', false);
    }

    public function addGroupAction() {
        $type = 'group';
        $oper = $this->_getParam('oper');
        $outerEdit = !empty($oper) && $this->_request->isXmlHttpRequest() ? true : false;

        if ($outerEdit) {
            $this->_helper->viewRenderer->setNoRender(true);
        }

        $formConfig = $this->_helper->moduleConfig('forms/'.$type);
        $form = new Workset_Form($formConfig);

        //транслятор формы
        $form->setTranslator(
            $this->_translate,
            $this->_helper->moduleConfig->getConfig(array('lang', $this->_locale, 'validators'), null, true)
        );

        if ($this->_request->isPost()) {
            try {
                $post = $this->_request->getPost();

                //редактирование через внешнюю форму (jqGrid)
                if ($outerEdit) {
                    $post = $this->_helper->utils->addPrefix($post, $type);
                }

                if ($form->isValid($post)) {
                    $values = $form->getValues();
                    $values = $this->_helper->utils->stripPrefix($values, $type);

                    $storage = new Users_Model_Access_Group_Storage_Table();
                    $object = $storage->create($values);
                    $object->save();

                    if (!$this->_request->isXmlHttpRequest()) {
                        $this->_helper->redirector->gotoSimple('list-'.$type);
                    } else {
                        return;
                    }
                }

                throw new Workset_Model_Exception($form->getCustomMessages(Workset_Form::ERROR_CODE), Workset_Form::ERROR_CODE);

            } catch (Zend_Exception $e) {
                $this->_helper->application->throwException($e, null, false);
            }
        }

        $backToListUrl = $this->_helper->url('list-'.$type);

        $this->view->form = $form;
        $this->view->backurl = $backToListUrl;
    }

    public function editGroupAction() {
        $type = 'group';
        $id = (int)$this->_getParam('id');

        $storage = new Users_Model_Access_Group_Storage_Table();
        $object = $storage->getOne($id);

        $oper = $this->_getParam('oper');
        $outerEdit = !empty($oper) && $this->_request->isXmlHttpRequest() ? true : false;

        if ($outerEdit) {
            $this->_helper->viewRenderer->setNoRender(true);
        }

        $formConfig = $this->_helper->moduleConfig('forms/'.$type);
        $form = new Workset_Form($formConfig);

        //транслятор формы
        $form->setTranslator(
            $this->_translate,
            $this->_helper->moduleConfig->getConfig(array('lang', $this->_locale, 'validators'), null, true)
        );

        if ($this->_request->isPost()) {
            try {
                $post = $this->_request->getPost();

                //редактирование через внешнбб форму (jqGrid)
                if ($outerEdit) {
                    $post = $this->_helper->utils->addPrefix($post, $type);
                }

                if ($form->isValid($post)) {
                    $values = $form->getValues();
                    $values = $this->_helper->utils->stripPrefix($values, $type);

                    $object->setData($values);
                    $object->save();

                    if (!$this->_request->isXmlHttpRequest()) {
                        $this->_helper->redirector->gotoSimple('list-'.$type);
                    } else {
                        return;
                    }
                }

                throw new Workset_Model_Exception($form->getCustomMessages(Workset_Form::ERROR_CODE), Workset_Form::ERROR_CODE);

            } catch (Zend_Exception $e) {
                $this->_helper->application->throwException($e, null, false);
            }
        } else {
            foreach ($object->toArray() as $key => $value) {
                $key = $type.'_'.$key;
                if ($element = $form->getElement($key)) {
                    $element->setValue($value);
                }
            }
        }

		$this->view->backurl = $this->_helper->url('list-'.$type);
        $this->view->form = $form;
        $this->render('add-'.$type);
    }

    public function deleteGroupAction() {
 		$type = 'group';
        $this->_helper->viewRenderer->setNoRender(true);

        $listId = $this->_helper->application->getListId('id', true);

        if (empty($listId)) {
            throw $this->_helper->application->throwException(null, 404);
        }

        $filter = array('id in(?)' => $listId);

        $storage = new Users_Model_Access_Group_Storage_Table();
        $items = $storage->getAll($filter);

        try {
            foreach ($items as $object) {
                $object->delete();
            }
        } catch (Zend_Exception $e) {
            $this->_helper->application->throwException($e);
        }

        if (!$this->_request->isXmlHttpRequest()) {
            $redirect = $this->_helper->url('list-'.$type);
            $this->_redirect($redirect);
        }
    }

    public function addRoleGroupAction() {
        $this->_helper->viewRenderer->setNoRender(true);

        $roleId = (int)$this->_getParam('nodeid');
        $groupId = (int)$this->_getParam('id');

        if ($roleId < 1 || $groupId < 1) {
            throw $this->_helper->application->throwException('Wrong request params', 404);
        }

        $roleStorage = new Users_Model_Access_Role_Storage_Table();
        $groupStorage =  new Users_Model_Access_Group_Storage_Table();

        $role = $roleStorage->getOne($roleId);
        $group = $groupStorage->getOne($groupId);

        $role->linkToObject($group);

        if (!$this->_request->isXmlHttpRequest()) {
            $redirect = $this->_helper->url('list-role');
            $this->_redirect($redirect);
        }
    }

    public function deleteRoleGroupAction() {
        $this->_helper->viewRenderer->setNoRender(true);

        $roleId = (int)$this->_getParam('nodeid');
        $groupId = (int)$this->_getParam('id');

        if ($roleId < 1 || $groupId < 1) {
            throw $this->_helper->application->throwException('Wrong request params', 404);
        }

        $roleStorage = new Users_Model_Access_Role_Storage_Table();
        $groupStorage =  new Users_Model_Access_Group_Storage_Table();

        $role = $roleStorage->getOne($roleId);
        $group = $groupStorage->getOne($groupId);

        $role->unlinkObject($group);

        if (!$this->_request->isXmlHttpRequest()) {
            $redirect = $this->_helper->url('list-role');
            $this->_redirect($redirect);
        }
    }

	public function setRulesAction() {
		$this->_helper->viewRenderer->setNoRender(true);

        $roleId = (int)$this->_getParam('nodeid');
        $data = $this->_getParam('id');

        if (!is_array($data)) {
            if (empty($data)) {
                $data = array();
            } else {
                $this->_helper->application->throwException('Wrong request data type', 404);
            }
        }

        $roleStorage = new Users_Model_Access_Role_Storage_Table();
        $resourceStorage = new Users_Model_Access_Resource_Storage_Table();
        $privilegeStorage = new Users_Model_Access_Privilege_Storage_Table();

        $role = $roleStorage->getOne($roleId);

        //сохраненные правила
        $rules = $role->getRules()->toArray(array(
            'resource_id',
            'privilege_id'
        ));

        $rid = array();

        //добавление/перезапись правил
        if (!empty($data)) {
            //ID ресурсов
            $rid = $this->_helper->application->getListId(array_keys($data));
        }
        //удаление сохраненных ранее правил
        foreach ($rules as $rule) {
           $rid[] =  $rule[0];
        }

        //список ресурсов
        if (!empty($rid)) {
            $resources = $resourceStorage->getAll(array('id in(?)' => $rid));
        } else {
            $resources = array();
        }

		$result = array();
		$container = array();

        foreach ($resources as $resource) {

            $pid = isset($data[ $resource->getId() ]) ? $this->_helper->application->getListId($data[ $resource->getId() ]) : array();

            $container[] = $resource;

            $privileges = $privilegeStorage->getAllByResource($resource);

			foreach ($privileges as $privelege) {

				if (in_array($privelege->getId(), $pid)) {

					//правило уже добавлено
					if (in_array(array( $resource->getId(), $privelege->getId() ), $rules)) {

						$result['add'][] = array(
							'role_id' => $role->getId(),
							'resource_id' => $resource->getId(),
							'privilege_id' => $privelege->getId()
						);

					} else {
                        //добавляем новое правило
					    $result['add'][] = $role->addRule($resource, $privelege);
                    }

					continue;

				}

                $container[] = $privelege;
			}
        }

		$resource = null;

		foreach ($container as $object) {
			if ($object instanceof Users_Model_Access_Resource) {
				$resource = $object;
				continue;
			}

			if (null !== $resource && $object instanceof Users_Model_Access_Privilege) {
				if (in_array(array( $resource->getId(), $object->getId() ), $rules)) {
					$result['add'][] = $role->deleteRule($resource, $object);
				}
			}
		}

        if ($this->_request->isXmlHttpRequest()) {
            $this->_helper->json($result, true);
        } else {
            $redirect = $this->_helper->url('list-role');
            $this->_redirect($redirect);
        }
	}

    public function deleteRuleAction() {
        $this->_helper->viewRenderer->setNoRender(true);
    }

	/**
	 * (non-PHPdoc)
	 * @see application/modules/users/models/Users_Model_Controller#_initProfileObjects()
	 */
	protected function _initProfileObjects() {
		// Создание объекта пользователя.
		try {
			$this->_oProfileUser = Users_Model_User::getById($this->_request->getParam('id',0));
		}
		catch (Exception $oException) {
			throw new Zend_Exception($oException->getMessage(),404);
		}

		// Профайлы администраторов системы доступны для редактирования только
		// администраторам. Остальные профайлы могут редактировать только поль-
		// зователи обладающие соответствующими правами.
		$this->_bReadOnly = ($this->_oProfileUser->isAdmin() && !Users_Model_User::getUser()->isAdmin())
			|| (!Users_Model_User::getUser()->isAllowed('AlienProfiles','change'));

		if ($this->_bReadOnly && $this->_request->isPost()) {
			throw new Zend_Excpetion('You do not have rights to change this profile.',403);
		}

		// Вызов родительского метода инициализации объектов.
		parent::_initProfileObjects();

		if ($this->_oProfileForm) {
			// Т.к. работаем в админке, то нам не нужно подтверждение действия вводом пароля.
			$this->_oProfileForm->removeElement('user_password');

			// Логины в админке нельзя менять, т.к. тогда пользователь не сможет войти в систему.
			// Если сменить пароль, то пользователь сможет его восстановить по е-mail.
			$this->_oProfileForm->removeElement('user_login');
		}
	}

	/**
	 * Проверка наличия идентификатора пользователя.
	 *
	 * @return boolean
	 */
	protected function _testUserId($sUri = '/users/admin/profile') {
		// Проверка наличия в запросе параметра - идентификатора пользователя.
		if (intval($this->_request->getQuery('id',0)) < 1) {
			// Создание объекта формы запроса идентификатора или логина пользователя.
			$aFormConfig = $this->_helper->moduleConfig(self::FORM_CONFIG_ASK_USER_ID);
			$this->view->form = $oForm = new Users_Form_Login($aFormConfig);

			// Если есть POST данные и они прошли проверку, то перенаправляем на профиль.
			if ($this->_request->isPost() && $oForm->isValid($this->_request->getPost())) {
				if ($sLogin = $oForm->getValue('login')) {
					$iId = Users_Model_User::getByLogin($sLogin)->getId();
				}
				elseif (!$iId = intval($oForm->getValue('id'))) {
					return false;
				}

				$this->_response->setRedirect("$sUri?id=$iId",302);
			}

			return false;
		}

		return true;
	}

	/**
	 * Получение списка элементов на основе Ajax запроса из jqGrid.
	 *
	 * @param string $sModelClass
	 * @param array $aFilter
	 * @param array $aColModel
	 * @param stdClass $oResponse
	 * @return Iterator
	 */
	protected function _getList($sModelClass,$aFilter,$aColModel,&$oResponce) {
		$oResponce instanceof stdClass || $oResponce = new stdClass();

		// Инициализация переменных и получение параметров.
		$sDefOrderBy  = ($a = reset($aColModel)) ? $a['name'] : 'id';
		$iPageNum     = intval($this->_request->getParam('page',1) - 1);
		$iRowCount    = intval($this->_request->getParam('rows',25));
		$sOrderField  = trim($this->_request->getParam('sidx',$sDefOrderBy));
		$sOrderVector = strtolower($this->_request->getParam('sord','asc'));

		// Задание правил отбора записей.
		$iTotalRows = call_user_func(array($sModelClass,'getCount'),$aFilter);

		// Проверка параметров.
		$iRowCount    = max(2,min($iRowCount,1000));
		$iPageCount   = ceil($iTotalRows / $iRowCount);
		$iPageNum     = max(0,min($iPageNum, $iPageCount - 1));

		$sOrderField  = array_search($sOrderField,array_map('reset',$aColModel)) !== false
			? $sOrderField
			: $sDefOrderBy;
		$sOrderVector = $sOrderVector == 'desc' ? 'desc' : 'asc';

		// Задание параметров сортировки и диапозона выводимых строк.
		$aOrder = array($sOrderField => $sOrderVector);
		$aLimit = array($iRowCount,0,$iPageNum);

		// Получение данных для объекта - ответа.
		$oResponce->page = $iPageNum + 1; // Номер текущей страницы.
		$oResponce->total = $iPageCount;  // Количество страниц.
		$oResponce->records = $iTotalRows; // Общее количество записей.
		$oResponce->rows = array();

		// Возращение итератора в вызвающий метод.
		return call_user_func(array($sModelClass,'getList'),$aFilter,$aOrder,$aLimit);
	}
}
?>